// 将XMLHttpRequest封装成fetch风格的函数
	function xhrFetch(url, options = {}) {
		return new Promise((resolve, reject) => {
			const xhr = new GM_xmlhttpRequest();
			
			// 设置请求方法和URL
			xhr.open(options.method || 'GET', url);
			
			// 设置请求头
			if (options.headers) {
				Object.keys(options.headers).forEach(key => {
					xhr.setRequestHeader(key, options.headers[key]);
				});
			}
			
			// 设置响应类型
			xhr.responseType = 'blob';
			
			// 处理超时
			if (options.timeout) {
				xhr.timeout = options.timeout;
			}
			
			// 处理加载完成
			xhr.onload = function() {
				if (xhr.status >= 200 && xhr.status < 300) {
					resolve({
						ok: true,
						status: xhr.status,
						statusText: xhr.statusText,
						blob: () => Promise.resolve(xhr.response),
						arrayBuffer: () => Promise.resolve(xhr.response),
						text: () => {
							return new Promise((resolveText, rejectText) => {
								const reader = new FileReader();
								reader.onload = () => resolveText(reader.result);
								reader.onerror = () => rejectText(reader.error);
								reader.readAsText(xhr.response);
							});
						},
						json: () => {
							return new Promise((resolveJson, rejectJson) => {
								const reader = new FileReader();
								reader.onload = () => {
									try {
										resolveJson(JSON.parse(reader.result));
									} catch (e) {
										rejectJson(e);
									}
								};
								reader.onerror = () => rejectJson(reader.error);
								reader.readAsText(xhr.response);
							});
						}
					});
				} else {
					reject(new Error(`HTTP错误! 状态码: ${xhr.status}`));
				}
			};
			
			// 处理错误
			xhr.onerror = function() {
				reject(new Error('网络请求失败'));
			};
			
			// 处理超时
			xhr.ontimeout = function() {
				reject(new Error('请求超时'));
			};
			
			// 发送请求
			xhr.send(options.body || null);
		});
	}

	// 使用xhrFetch下载图片并创建视频
	async function downloadImagesAndCreateVideoWithFFmpeg(imageUrls) {
		const { createFFmpeg } = FFmpeg;
		// const ffmpeg = createFFmpeg({ log: true });
		const ffmpeg = createFFmpeg({ 
														log: true,
														corePath: 'https://unpkg.com/@ffmpeg/core-st@0.10.1/dist/ffmpeg-core.js',
														mainOptions: ['-pthreads', '1']
													});
		await ffmpeg.load();
		
		const canvas = document.createElement('canvas');
		const ctx = canvas.getContext('2d');
		canvas.width = 1368;
		canvas.height = 766;
		
		const imagePromises = [];
		
		for (let i = 0; i < imageUrls.length; i++) {
			const imageUrl = imageUrls[i];
			const frameNumber = i.toString().padStart(6, '0');
			
			const imagePromise = (async () => {
				try {
					// 使用封装的xhrFetch下载图片
					const response = await xhrFetch(imageUrl, {
						method: 'GET',
						timeout: 30000 // 30秒超时
					});
					
					if (!response.ok) {
						throw new Error(`HTTP ${response.status}`);
					}
					
					const blob = await response.blob();
					
					const img = new Image();
					await new Promise((resolve, reject) => {
						img.onload = resolve;
						img.onerror = reject;
						img.src = URL.createObjectURL(blob);
					});
					
					ctx.clearRect(0, 0, canvas.width, canvas.height);
					ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
					
					const frameBlob = await new Promise(resolve => {
						canvas.toBlob(resolve, 'image/jpeg', 0.8);
					});
					
					const frameData = await new Promise((resolve, reject) => {
						const reader = new FileReader();
						reader.onload = () => resolve(new Uint8Array(reader.result));
						reader.onerror = reject;
						reader.readAsArrayBuffer(frameBlob);
					});
					
					ffmpeg.FS('writeFile', `frame-${frameNumber}.jpg`, frameData);
					
					console.log(`已处理第 ${i + 1}/${imageUrls.length} 帧`);
					return true;
					
				} catch (error) {
					console.error(`处理图片 ${imageUrl} 失败:`, error);
					return false;
				}
			})();
			
			imagePromises.push(imagePromise);
			
			// 添加延迟
			if (i % 5 === 0) {
				await new Promise(resolve => setTimeout(resolve, 100));
			}
		}
		
		const results = await Promise.all(imagePromises);
		const successfulFrames = results.filter(Boolean).length;
		
		if (successfulFrames === 0) {
			throw new Error('没有成功下载任何图片');
		}
		
		try {
			await ffmpeg.run(
				'-framerate', '1',
				'-i', `frame-%06d.jpg`,
				'-c:v', 'libx264',
				'-pix_fmt', 'yuv420p',
				'-crf', '23',
				'-preset', 'fast',
				'output.mp4'
			);
			
			const videoData = ffmpeg.FS('readFile', 'output.mp4');
			const videoBlob = new Blob([videoData.buffer], { type: 'video/mp4' });
			const videoUrl = URL.createObjectURL(videoBlob);
			
			// 清理临时文件
			for (let i = 0; i < successfulFrames; i++) {
				const frameNumber = i.toString().padStart(6, '0');
				try {
					ffmpeg.FS('unlink', `frame-${frameNumber}.jpg`);
				} catch (e) {
					// 忽略错误
				}
			}
			
			return videoUrl;
			
		} catch (error) {
			console.error('FFmpeg视频合成失败:', error);
			throw error;
		}
	}
	
	// 使用示例
	async function testCreateVideoFromImages() {
		try {
			console.log('开始下载图片并合成视频...');
			
			const imageUrls = [
				"https://nineyu.com/fa2d4a35-0281-4d90-b71f-438e32892df8/seek/_0.jpg",
				"https://nineyu.com/fa2d4a35-0281-4d90-b71f-438e32892df8/seek/_1.jpg",
				"https://nineyu.com/fa2d4a35-0281-4d90-b71f-438e32892df8/seek/_2.jpg",
				"https://nineyu.com/fa2d4a35-0281-4d90-b71f-438e32892df8/seek/_3.jpg",
				"https://nineyu.com/fa2d4a35-0281-4d90-b71f-438e32892df8/seek/_4.jpg",
				"https://nineyu.com/fa2d4a35-0281-4d90-b71f-438e32892df8/seek/_5.jpg"
			];
			
			const videoUrl = await downloadImagesAndCreateVideoWithFFmpeg(imageUrls);
			console.log('视频合成完成:', videoUrl);
			
			// 创建视频元素并显示
			const video = document.createElement('video');
			video.src = videoUrl;
			video.controls = true;
			video.autoplay = true;
			video.style.width = '100%';
			video.style.maxWidth = '800px';
			
			// 添加到页面
			const container = document.getElementById('.plyr__video-wrapper') ;
			container.appendChild(video);
			
		} catch (error) {
			console.error('视频创建失败:', error);
			throw error;
		}
	}